package com.hc;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

//切面类：定义要额外扩展的功能
@Component
@Aspect //注解方式配置AOP
@Order(2)//指定多个切面类的优先级
public class UserHelperAspect {
    //额外扩展功能对象
    @Autowired
    private TransicationManager manager;

    /**
     * 环绕通知方法：被@Around注解,必须要有一个ProceedingJoinPoint参数
     * 粗粒度表达式：within(com.hc.*) 只定位到目标类
     * 细粒度表达式：execution(* com.hc..*.*(..)) 可定位到目标类的方法,本方法返回值必须是Object
     *            任意返回值 包.任意类.任意方法(任意参数)
     */
    @Around(value = "execution(* com.hc.UserHelper.*(..))") //注解方式配置AOP
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        manager.open(); //目标方法前执行额外操作
        Object o = joinPoint.proceed();
        manager.commit(); //目标方法后执行额外操作
        return o;
    }
    @Pointcut(value = "execution(* com.hc.UserHelper.*(..))")
    public void pointCut(){

    }
    @Before(value = "execution(* com.hc.UserHelper.*(..))")
    public void before(JoinPoint joinPoint){
        System.out.println("前置通知");
    }
    @AfterReturning(value = "pointCut()") //简化写法
    public void after(JoinPoint joinPoint){
        System.out.println("后置通知");
    }
    @AfterThrowing(value = "execution(* com.hc.UserHelper.*(..))",throwing = "throwable")
    public void throwException(JoinPoint joinPoint, Throwable throwable){
        System.out.println("异常通知");
    }
    @After(value = "execution(* com.hc.UserHelper.*(..))")
    public void finalEx(){
        System.out.println("最终通知");
    }
}
